﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.ZLog;

namespace UtilZ.Dotnet.Ex.Model
{
    /// <summary>
    /// 缓存数据
    /// </summary>
    public class BufferDataReader : BinaryReader
    {
        private readonly BufferData _bufferData;
        /// <summary>
        /// 原始缓存数据
        /// </summary>
        public BufferData BufferData
        {
            get { return _bufferData; }
        }


        private BufferDataReader(BufferData bufferData, Stream stream)
            : base(stream)
        {
            this._bufferData = bufferData;
        }

        private BufferDataReader(BufferData bufferData, Stream stream, Encoding encoding)
            : base(stream, encoding)
        {
            this._bufferData = bufferData;
        }

        /// <summary>
        /// 创建一个缓存数据读取对象
        /// </summary>
        /// <param name="bufferData">缓存数据</param>
        /// <param name="encoding">数据编码类型</param>
        /// <returns>一个缓存数据读取对象</returns>
        /// <exception cref="NotSupportedException"></exception>
        public static BufferDataReader Create(BufferData bufferData, Encoding encoding = null)
        {
            if (bufferData == null)
            {
                throw new ArgumentNullException(nameof(bufferData));
            }

            Stream stream;
            switch (bufferData.DataType)
            {
                case BufferDataType.Bytes:
                    stream = new MemoryStream(bufferData.Bytes);
                    break;
                case BufferDataType.Stream:
                    stream = bufferData.Stream;
                    break;
                case BufferDataType.File:
                    stream = new FileStream(bufferData.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    bufferData.UpdateFileBufferLength(stream.Length);
                    break;
                default:
                    throw new NotSupportedException(bufferData.DataType.ToString());
            }

            stream.Seek(bufferData.Offset, SeekOrigin.Begin);

            if (encoding == null)
            {
                return new BufferDataReader(bufferData, stream);
            }
            else
            {
                return new BufferDataReader(bufferData, stream, encoding);
            }

        }

    }


}
